#!/bin/bash
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-host-download-bootstrap-pkgs.sh
# author: david921518@qq.com

################
# global vars
GLB_WORK_DIR=
################

user=$(whoami)

# 定义日志格式-前缀
log_prefix="[dl-bootstrap-pkgs]"
# 定义日志目录和文件名
log_file_dir="/var/log/kpc/huangdi"
log_file_path="$log_file_dir/host-build.log"

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  if [ "$user" == "root" ]; then
    echo "$curtime $log_prefix $@" >>$log_file_path
    #sleep 0.1
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    #sleep 0.1
    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #sleep 0.1
  fi
}

function get_work_dir()
{
  ################
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/host/huangdi-host-download-bootstrap-pkgs.sh
  ################

  local real_path=$(realpath $0)
  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"
}

function download_pkgs()
{
  local real_path=$(realpath $0)
  local work_dir=$(dirname $real_path)
  local bs_dir=$work_dir/../bootstrap
  local pre_dir=$bs_dir/preinstall
  local dl_file=$pre_dir/host-download.sh
  local bs_file=$pre_dir/bootstrap_ipks.txt

  if [ -f $bs_file ]; then
    log "$dl_file $bs_file"
    $dl_file "$bs_file"
  else
    bs_file=$pre_dir/bootstrap_apks.txt
    if [ -f $bs_file ]; then
      log "$dl_file $bs_file"
      $dl_file "$bs_file"
    else
      log "no bootstrap pkgs list file"
    fi
  fi
}

# 0. init scripts
log_init
get_work_dir
cd "$GLB_WORK_DIR"

# 1. Make work dir
download_pkgs

